<template>
    <div>
        <el-form :model="passwordForm" style="width: 350px;" ref="ruleFormRef" :rules="rules" label-width="80px"
            label-position="right">
            <el-form-item label="旧密码" prop="old_password">
                <el-input v-model="passwordForm.old_password" type="password" placeholder="请输入旧密码" show-password />
            </el-form-item>
            <el-form-item label="新密码" prop="new_password">
                <el-input v-model="passwordForm.new_password" type="password" placeholder="请输入新密码" show-password />
            </el-form-item>
            <el-form-item label="确认密码" prop="againPassword">
                <el-input v-model="passwordForm.againPassword" type="password" placeholder="请再次输入新密码" show-password />
            </el-form-item>
            <el-form-item>
                <el-button @click="Back">取消</el-button>
                <el-button type="primary" @click="Submit(ruleFormRef)">提交</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup lang='ts'>
import { setPassword } from '../api/index'
import { useRouter } from 'vue-router'
import { ElMessage, FormInstance } from 'element-plus'
import { ref } from 'vue'
const router = useRouter()
const ruleFormRef = ref<FormInstance>()
interface passwordForm {
    old_password: string
    new_password: string
    againPassword: string
}
const passwordForm = ref<passwordForm>({
    old_password: '',
    new_password: '',
    againPassword: ''
})
const Back = () => {
    router.push('/')
}
const rules = ref({
    old_password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 16, message: '密码应为6~16位', trigger: 'blur' },
    ],
    new_password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 16, message: '密码应为6~16位', trigger: 'blur' },
    ],
    againPassword: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 16, message: '密码应为6~16位', trigger: 'blur' },
    ],
})
const Submit = async (formEl: any) => {

    if (!formEl) return
    await formEl.validate(async (valid: any, fields: any) => {
        if (valid) {
            if (passwordForm.value.new_password === passwordForm.value.againPassword) {
                let res = await setPassword({
                    new_password: passwordForm.value.new_password,
                    old_password: passwordForm.value.old_password
                })
                if (res.data.code === 0) {
                    ElMessage({
                        message: '修改成功',
                        type: 'success',
                    })
                    router.push('/login')
                } else {
                    ElMessage.error('旧密码输入错误')
                }

            } else {
                ElMessage.error('两次密码不一致')
            }
        } else {
            ElMessage.error('提交失败')
        }
    })

}
</script>
<style scoped lang='less'></style>